/**
 * jQuery polling plugin
 */
(function($) {
    $.fn.poll = function(options){
        var $this = $(this);
        // extend our default options with those provided
        var opts = $.extend({}, $.fn.poll.defaults, options);
        setInterval(update, opts.interval);

        // method used to send ajax request
        function update(){
            $.ajax({
                type: opts.type,
                url: opts.url,
                success: opts.success,
                error: opts.error
            });
        };
        
        // start the first update
        update();
    };

    // default options
    $.fn.poll.defaults = {
        type: "POST",
        url: ".",
        success: '',
        error: '',
        interval: 2000
    };
    
})(jQuery);

/**
 * Loads User Categories and fullfill a Select
 * 
 * @param jQuery box  The Select object to fullfill
 * @param String url to call 
 * @param String callback function to signal completed task
 * @return void
 */
function loadUserCategory(box, url, callback) {
    jQuery.ajax({
        type: "POST",
        url: url,
        dataType: "json",
        success: function(j) {
    		var options = '';
    		for (var i = 0; i < j.length; i++) {
    			options += '<option value="' + j[i].oid + '"';
    			options += '>' + j[i].name + '</option>';
    		}
    		box.html(options);
    		
    		if(callback != null) {
    			callback();
    		}
	    },
	    error: function(xhr, textStatus, errorThrown) {
           
        }
    });
}

/**
 * Makes an ajax request to check for volid url and 
 * to retrieve feed's informations if available
 * 
 * @param String url The url to route the request
 * @param String feed The feed's url
 * @param callback The function to be called on request completion
 * @return void
 */
function getfeedinfo(url, feed, callback) {
    if (!feed.length == 0) {
	    jQuery.ajax({
	        type: "POST",
	        url: url,
	        data: {feedurl: feed},
	        dataType: "json",
	        success: function(data) {
	            // Execute the callback passing it the result
	        	callback(data);
	        },
	        error: function(xhr, textStatus, errorThrown) {
	            //TODO Process errors with a specifc callback
	        	jQuery.facebox(xhr.responseText);
	        }
	    });
    }
    
    return;
}

/**
 * Make an ajax request to check for username
 * 
 * @param String url The url to route the request
 * @param String user The username
 * @param callback The function to be called on request completion
 * @return void
 */
function checkUsername(url, user, callback) {
    if (!user.length == 0) {
	    jQuery.ajax({
	        type: "POST",
	        url: url,
	        data: {username: user},
	        dataType: "json",
	        success: function(data) {
	            // Execute the callback passing it the result
	        	callback(data.result);
	        },
	        error: function(xhr, textStatus, errorThrown) {
	            //TODO Process errors with a specifc callback
	        	jQuery.facebox(xhr.responseText);
	        }
	    });
    }
    
    return;
}

/**
 * Process Jason response validation
 *  
 * @param data JSON response
 * @return Error messages 
 */
function parseJsonValidation(data) {
    var result = "";
    
    for (var elem in data) {
        result += elem + " " + data[elem] + "<br/>";
    }

    return result;
}

/**
 * Set a Value on Element
 * 
 * @param int elementID 
 * @param int valueToSet 
 * @param String url to call
 * @param String callback function to signal completed task
 * @return void
 */
function setFlag(elementID, valueToSet, url, callback) {
    jQuery.ajax({
        type: "POST",
        url: url,
        dataType: "json",
        data: {elementID: elementID, valueToSet: valueToSet},
        success: function(data) {
        	callback(data);
        },
        error: function(xhr, textStatus, errorThrown) {
        	
        }
    });
}

/**
 * Execute common tasks like Edit/Delete
 * 
 * @param int elementID to wich apply the request
 * @param String url to call
 * @param String callback function to signal completed task
 * @return void
 */
function executeRequest(elementID, url, callback) {
    jQuery.ajax({
        type: "POST",
        url: url,
        dataType: "json",
        data: {elementID: elementID},
        success: function(data) {
        	callback(data);
        },
        error: function(xhr, textStatus, errorThrown) {
        	
        }
    });
}

/**
 * Load the content obtained by a request made to the given url
 * Content is injected in a container passed in as parameter
 * 
 * @param String url to call
 * @param jQuery box object to inject in
 * @param String callback function to signal completed task
 * @return void
 */
function loadView(url, box, callback) {
    jQuery.ajax({
        type: "POST",
        url: url,
        success: function(data) {
    		if (box != null) {
    			box.html(data).show('blind', 100);
    		}
    		
            if (callback != null) {
            	callback(data);
            }
        },
        error: function(xhr, textStatus, errorThrown) {
           
        }
    });
}

/**
 * Init configuration for modal confirmation dialog
 * 
 * @param jQuery object boxdialog 
 * @return void
 */
function initConfirmBox(boxdialog) {
	boxdialog.hide();
    
	boxdialog.dialog({
        bgiframe: true,
        resizable: true,
        autoOpen: false,
        modal: true,
        height: 'auto',
        width: 'auto',
        title: '',
        overlay: {
            backgroundColor: '#000',
            opacity: 0.5
        }
    });
}

/**
 * Open the confirmation dialog
 * 
 * @param jQuery object boxdialog 
 * @param an array of boxTitle, msgStatus and msg
 * @return void
 */
function showConfirmDialog(boxdialog, options) {
	boxdialog.empty();
	boxdialog.dialog('option', 'title', options.boxTitle);
    
	boxdialog.html('<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span></p>');
    boxdialog.children('p').append(options.msgStatus);
    boxdialog.append("<p>" + options.msg + "</p>");
    
    boxdialog.dialog('open');      
}

